
import AppManagement from "AppManagement";
import Aisle from "component/Aisle";

export interface IGenieOptions {
    /** app的容器 */
    appContainer: HTMLDivElement | null;

    /** app id */
    id: string;
}

export default class Genie {

    /** sdk 的容器 */
    top: Window = window;

    /** app 的window */
    appWindow?: Window | null;

    /** app 的容器 */
    appContainer: HTMLElement | null;

    /** app 的容器 */
    appHead?: HTMLElement | null;

    /** 应用ID */
    id: string;

    /** 应用通道 */
    aisle?: Aisle;

    constructor(options: IGenieOptions) {
        this.id = options.id;
        this.top = window;
        this.appContainer = options.appContainer;
    }

    init = async () => {
        await this.loadApp();
    }

    /** 加载应用 */
    private loadApp = () => new Promise<void>(resolve => {
        const head = window.document.querySelector(`#mic-head>#${this.id.replace(/\./g, '\\.')}`) as HTMLDivElement;
        const app = AppManagement.instance.getApp(this.id);
        if (!app) {
            resolve();
            return;
        }

        if (!head) {
            const appHead = window.document.createElement('div');
            const appIframe = window.document.createElement('iframe');
            appHead.id = this.id;
            appHead.appendChild(appIframe);
            appIframe.src = app.url;
            window.document.querySelector('#mic-head')?.appendChild(appHead);
            this.appHead = appHead;
            this.appWindow = appIframe.contentWindow as Window;
            appIframe.addEventListener("load", () => {
                this.aisle = new Aisle({ id: this.id, appHead: appHead, appWindow: this.appWindow as any });
                resolve()
            });
        } else {
            const appIframe = head.querySelector('iframe') as HTMLIFrameElement;
            this.appHead = head;
            this.appWindow = appIframe.contentWindow as Window;
            this.aisle = this.appWindow['$_MicAisle'];

            if (this.appWindow ? this.appWindow['$_MicPack'] : undefined) {
                this.aisle = (this.appWindow as any)['$_MicAisle'];
                resolve();
            } else {
                appIframe.addEventListener("load", () => {
                    this.aisle = (this.appWindow as any)['$_MicAisle'];
                    resolve()
                });
            }
        }
    })

    /** 清楚回收 */
    distinct = () => {
        try {
            if (window.document.querySelectorAll(`[app-id="${this.id.replace(/\./g, '\\.')}"]`).length === 0) {
                window.document.querySelector('#mic-head')?.removeChild(window.document.querySelector(`#mic-head>#${this.id.replace(/\./g, '\\.')}`) as any)
            }
        } catch (error) {
        }
    }

    getModule = (moduleName = 'default') => {
        return this.aisle?.micPack[moduleName]
    }
}
